package org.lanqiao.taru.controller;

import org.lanqiao.taru.common.Result;
import org.lanqiao.taru.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import   java.util.List;

@RestController
public class ProductController {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 临时往redis数据库插入数据
     * @return
     */
    @RequestMapping("/add")
    public Result add() {
        Product  product  =new Product("A","鼠标","","50.50");
        Product  product1  =new Product("B","键盘","","80.50");
        Product  product2  =new Product("C","显示器","","1000.50");
        Product  product3  =new Product("D","硬盘","","200.50");
        redisTemplate.opsForHash().put("Products",product.getId(),product);
        redisTemplate.opsForHash().put("Products",product1.getId(),product1);
        redisTemplate.opsForHash().put("Products",product2.getId(),product2);
        redisTemplate.opsForHash().put("Products",product3.getId(),product3);
        return Result.OK("成功","") ;
    }


    /**
     * 查询单个的商品
     * @return
     */
    @RequestMapping("/products/{id}")
    public Result getById(@PathVariable("id")  String id) {
        if(redisTemplate.opsForHash().hasKey("Products",id)){
            return Result.OK("成功",redisTemplate.opsForHash().get("Products",id)) ;
        }else{
            //从数据库查
            //往redis放一份
           return  Result.OK("成功","数据库查询结果模拟");

        }

    }

    /**
     * 查询所有商品
     * @param
     * @return
     */
    @RequestMapping("/products/list")
    public Result list(){
       List<Product>    list =  redisTemplate.opsForHash().values("Products");
       return Result.OK("所有的商品查询成功",list);
    }


}